
import { Select } from 'antd';
import { useEffect, useState } from 'react';
import { listErrorCodeDirGroup } from '@/services/doc/api'
const { Option, OptGroup } = Select;


const ApiErrorCodeSelect = (props) => {

    const {
        value,
        defaultValue,
        onChange,
        projectId,
    } = props

    const [errorCodeData, setErrorCodeData] = useState({});
    const [errorCodeMap, setErrorCodeMap] = useState({});
    const [realValue,setRealValue] = useState()
    useEffect(() => {
        if (value) {
            if (Object.keys(errorCodeData) <= 0) {
                setErrorCodeData({
                    list: value
                })
            }
            setRealValue(value.map(item => item.id))
        }
    }, [value])

    useEffect(() => {
        if (projectId) {
            listErrorCodeDirGroup(projectId).then((result) => {
                let errorCodeData = result?.data;
                setErrorCodeData(errorCodeData)
                if (errorCodeData) {
                    let errorCodeMap = {}
                    errorCodeData.list && errorCodeData.list.map(item => {
                        errorCodeMap[item.id] = item
                    })
                    errorCodeData.subDirList && errorCodeData.subDirList.map(dir => {
                        dir.list && dir.list.map(item => {
                            errorCodeMap[item.id] = item
                        })
                    })
                    setErrorCodeMap(errorCodeMap)
                }
            })
        }
    }, [projectId])

    const onSelectChange = (values) => {
        setRealValue(values)
        if (onChange) {
            let relData = values ? values.map(v => {
                return {
                    id: errorCodeMap[v].id,
                    type: errorCodeMap[v].type,
                    description: errorCodeMap[v].description,
                    name: errorCodeMap[v].name,
                }
            }) : [];
            onChange(relData)
        }
    }

    return <Select
        mode="multiple"
        onChange={onSelectChange}
        value={realValue}
        placeholder="请选择错误码"
        filterOption={(inputValue, option) => {
            let lebal = errorCodeMap[option.key]?.name + "*" + errorCodeMap[option.key]?.description
            return lebal.indexOf(inputValue) > -1;
        }}
    >
        {errorCodeData.list && errorCodeData.list.map(item => <Option key={item.id} value={item.id}>{item.name}:{item.description}</Option>)}
        {errorCodeData.subDirList && errorCodeData.subDirList.map(dir => <OptGroup key={dir.id} label={dir.name}>
            {dir.list && dir.list.map(item => <Option key={item.id} value={item.id}>{item.name}:{item.description}  </Option>)}
        </OptGroup>)}
    </Select>
}

export default ApiErrorCodeSelect;